package org.dru.clay.respository.transport.ssh;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.userauth.method.AuthMethod;

import com.jcraft.jsch.agentproxy.AgentProxy;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.Identity;
import com.jcraft.jsch.agentproxy.sshj.AuthAgent;

public class Test {

	public static void main(String[] args) throws Exception {
		final SSHClient ssh = new SSHClient();
		ssh.loadKnownHosts();

		ssh.connect("dev4");
		try {
			AgentProxy agentProxy = getAgentProxy();
			if (agentProxy == null) {
				System.err.println("No agentProxy");
				System.exit(0);
			}
			ssh.auth(System.getProperty("user.name"), getAuthMethods(agentProxy));
			final Session session = ssh.startSession();
			try {
				final Command cmd = session.exec("ping -c 1 google.com");
				System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
				cmd.join(5, TimeUnit.SECONDS);
				System.out.println("\n** exit status: " + cmd.getExitStatus());
			} finally {
				session.close();
			}
		} finally {
			ssh.disconnect();
		}
	}

	private static AgentProxy getAgentProxy() {
		Connector connector = getAgentConnector();
		if (connector != null)
			return new AgentProxy(connector);
		return null;
	}

	private static Connector getAgentConnector() {
		try {
			return ConnectorFactory.getDefault().createConnector();
		} catch (AgentProxyException e) {
			System.err.println(e);
		}
		return null;
	}

	private static List<AuthMethod> getAuthMethods(AgentProxy agent) throws Exception {
		Identity[] identities = agent.getIdentities();
		List<AuthMethod> result = new ArrayList<AuthMethod>();
		for (Identity identity : identities) {
			result.add(new AuthAgent(agent, identity));
		}
		return result;
	}
}
